#include "stdafx.h"
#include "Telnet.h"
#include "Log.h"

namespace Core
{
	TelnetClient::TelnetClient(Socket& p_Socket, Telnet& p_Telnet) : m_Telnet(p_Telnet), TelnetSocket(p_Socket)
	{
		TelnetSocket.StartReceiver();
	}

	void TelnetClient::Process()
	{
		RawData t_RawData;
		while(!TelnetSocket.IsReceiverEmpty())
		{
			try
			{
				t_RawData.Reset();
				TelnetSocket.Receive(t_RawData);
				m_Telnet.MessageReceived(this, t_RawData.ToString());
			}
			catch(...)
			{
			}
		}
	}

	void TelnetClient::Send(std::string p_Message)
	{
		RawData t_RawData;
		try
		{
			t_RawData.FromString(p_Message);
			TelnetSocket.Socket::Send(t_RawData);
		}
		catch(...)
		{
		}
	}

	Telnet::Telnet(unsigned short p_PortNumber) : TCPServer(p_PortNumber)
	{
		Timer::Start(100);
	}

	void Telnet::ConnectionReceived(Socket& p_Socket)
	{
		Log::GetSingleton().Write(LogLevel_Info, "Telnet Server is receiving connection from " + p_Socket.GetRemoteAddress().Address);
		TelnetClient* t_TelnetClient = new TelnetClient(p_Socket, *this);
		m_TelnetClients.push_back(t_TelnetClient);
		ConnectionReceived(t_TelnetClient);
	}

	void Telnet::ExecuteByInterval()
	{
		for(std::list<TelnetClient*>::iterator p=m_TelnetClients.begin(); p!=m_TelnetClients.end(); p++)
		{
			if(!(*p)->TelnetSocket.IsActive())
			{
				Log::GetSingleton().Write(LogLevel_Info, "Telnet Server is closing connection from " + (*p)->TelnetSocket.GetRemoteAddress().Address);
				delete *p;
				m_TelnetClients.erase(p);
				return;
			}
			(*p)->Process();
		}
	}
}
